import React from 'react';
import Pagination from 'react-ui-pagination';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();

import * as axios from 'axios';
axios.defaults.headers.post['Content-Type'] = window.GLOBAL.contentType;

export default class TableView extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            totalPageNum: 1,
            currentPage: 1,
            pageNum: 5,
            data: [],
            allData: [],
            content:[],
            totalNumber: 0,

        };
    }
    static defaultProps = {
        isService: false,
        url: "",
        method: "post",
        data: [],
        pageNum: 10,
        searchObject: null,
        diableInputPaginate: false,
        sort: null,
        dir: null,
        isInternalRendering: true,
        headerToken: "staffAuth",
        renderRow: ()=>{},
        onPageSelected: ()=>{},
        setHeaderToken: ()=>{},
    };
    static propTypes = {
        isService: React.PropTypes.bool.isRequired, //是否来自服务器（true: 服务器分页，false: 本地分页）
        url: React.PropTypes.string, //服务器请求 URL 地址
        method: React.PropTypes.string, //请求方法
        diableInputPaginate: React.PropTypes.bool, //是否禁用输入分页
        data: React.PropTypes.array, //本地数据源
        pageNum: React.PropTypes.number, //每页行数
        searchObject: React.PropTypes.object, //查询对象（默认: null）
        sort: React.PropTypes.string, //分页字段名
        dir: React.PropTypes.string,  //排序规则（ASC, DESC）
        renderRow: React.PropTypes.func,  //渲染行回调
        onPageSelected: React.PropTypes.func,  //页码选择回调
        totalPageNum: React.PropTypes.func,  //总页数回调
        isInternalRendering: React.PropTypes.bool,
        headerToken: React.PropTypes.string,  //设置 Token 名字
    };
    componentWillMount(){
        if(this.props.pageNum != undefined){
            this.setState({
              pageNum: this.props.pageNum
            })
        }
        this.setState({
            totalNumPage:this.state.totalPageNum
        });
    }
    componentDidMount(){
        this.refreshData();
    }
    refreshData(){
      if(this.props.isService != undefined){
          if(this.props.isService == false){
              if(this.props.data != undefined){
                if (Math.ceil(this.props.data.length / this.state.pageNum) >= 2){
                    var startIndex = (this.state.currentPage-1)*this.state.pageNum;
                    var endIndex = (this.state.currentPage)*this.state.pageNum;
                    this.setState({
                        totalPageNum: Math.ceil(this.props.data.length / this.state.pageNum),
                        data: this.props.data.slice(startIndex, endIndex),
                        allData: this.props.data
                    });
                }else{
                    this.setState({
                        totalPageNum: Math.ceil(this.props.data.length / this.state.pageNum),
                        data: this.props.data,
                        allData: this.props.data
                    });
                }
              }
          }else if(this.props.isService == true){
              if(this.props.url != undefined && this.props.method != undefined){
                if(sessionStorage.getItem(this.props.headerToken) != null){
                    axios.defaults.headers.common[this.props.headerToken] = sessionStorage.getItem(this.props.headerToken);
                }
                var me = this; this.state.currentPage = 1;
                var searchObject = {
                    pageSize: this.state.pageNum,
                    pageNumber: this.state.currentPage,
                    conditions: {}
                };
                if(this.props.searchObject != null){
                    searchObject.pageSize = this.state.pageNum;
                    searchObject.pageNumber = this.state.currentPage;
                    searchObject.conditions = this.props.searchObject;
                }
                if(this.props.sort != null && this.props.dir != null){
                    searchObject.sort = this.props.sort;
                    searchObject.dir = this.props.dir;
                }
                axios[this.props.method.toLowerCase()](this.props.url, searchObject)
                .then(function (response) {
                    if(response.data.code == 1){
                        var total = response.data.data.total;
                        var data = response.data.data.content;
                        me.setState({
                          data: data,
                          totalPageNum: response.data.data.totalPage,
                          content:response.data.data.content,
                          totalNumber: response.data.data.total
                        });
                        if(me.props.totalPageNum != undefined){
                            me.props.totalPageNum(total);
                        }
                        if(me.props.getServiceData != undefined){
                            me.props.getServiceData(data);
                        }
                    }else{
                        alert('对不起，分页异常');
                    }
                })
                .catch(function (response){
                    if(me.props.serviceError != undefined){
                        me.props.serviceError(response);
                    }
                    console.log(response);
                });
              }else{
                alert('对不起，分页请求参数不全。')
              }
          }
      }else{
          alert('对不起，请告诉分页方式。')
      }
    }

    onPageSelected(index){
        if(this.props.onPageSelected != undefined){
          this.props.onPageSelected(index);
        }
        if(this.props.isService == false){
            var startIndex = (index-1)*this.state.pageNum;
            var endIndex = (index)*this.state.pageNum;

            this.setState({
                data: this.state.allData.slice(startIndex,endIndex),
                currentPage: index
            });
        }else if(this.props.isService == true){
            if(this.props.url != undefined && this.props.method != undefined){
              if(sessionStorage.getItem(this.props.headerToken) != null){
                  axios.defaults.headers.common[this.props.headerToken] = sessionStorage.getItem(this.props.headerToken);
              }
              var me = this;
              var searchObject = {
                  pageSize: this.state.pageNum,
                  pageNumber: index,
                  conditions: {}
              };
              if(this.props.searchObject != null){
                  searchObject.pageSize = this.state.pageNum;
                  searchObject.pageNumber = index;
                  searchObject.conditions = this.props.searchObject;
              }
              if(this.props.sort != null && this.props.dir != null){
                  searchObject.sort = this.props.sort;
                  searchObject.dir = this.props.dir;
              }
              axios[this.props.method.toLowerCase()](this.props.url, searchObject)
              .then(function (response) {
                  if(response.data.code == 1){
                      var total = response.data.data.total;
                      var data = response.data.data.content;
                      me.setState({
                        data: data,
                        currentPage: index,
                        totalPageNum: response.data.data.totalPage,
                        totalNumber: response.data.data.total
                      });
                      if(me.props.getServiceData != undefined){
                          me.props.getServiceData(data);
                      }
                  }else{
                      alert('对不起，分页异常');
                  }
              })
              .catch(function (response) {
                  if(me.props.serviceError != undefined){
                      me.props.serviceError(response);
                  }
                  console.log(response);
              });
            }else{
              alert('对不起，分页请求参数不全。')
            }
        }
    }

    render(){
      if(this.props.isInternalRendering == true){
          return(
              <div>
                  <div id="divTable" className="row">
                      {
                          this.state.data.map((item,index) => {
                              return this.props.renderRow(item,index);
                          })
                      }
                  </div>
                  <Pagination
                    pageNum={this.state.totalPageNum}
                    diableInputPaginate={this.props.diableInputPaginate}
                    initialSelected={this.state.currentPage-1}
                    middleDisplayRange={5}
                    sideDislpayRange={2}
                    initialSelected={0}
                    prevLabel="上一页"
                    nextLabel="下一页"
                    inputOkBtnLabel="确定"
                    inputLabel={"页，共 "+ ((this.props.isService == true)?this.state.totalNumber:this.state.allData.length) +" 条"}
                    inputLabelInfo={"共 " + this.state.totalPageNum + " 页，去第"}
                    onPageSelected={this.onPageSelected.bind(this)}
                  />
              </div>
          );
      }else{
          return(
              <Pagination
                pageNum={this.state.totalPageNum}
                diableInputPaginate={this.props.diableInputPaginate}
                initialSelected={this.state.currentPage-1}
                middleDisplayRange={5}
                sideDislpayRange={2}
                initialSelected={0}
                prevLabel=" 上一页"
                nextLabel="下一页 "
                inputOkBtnLabel="确定"
                inputLabel={"页，共 "+ ((this.props.isService == true)?this.state.totalNumber:this.state.allData.length) +" 条"}
                inputLabelInfo={"共 " + this.state.totalPageNum + " 页，去第"}
                onPageSelected={this.onPageSelected.bind(this)}
              />
          );
      }
    }
}
